import React, { useEffect, useLayoutEffect, useState } from 'react';

import { Icon } from 'antd';
import { ActivityIndicator, DatePicker, InputItem, Modal, Picker, TextareaItem, Toast } from 'antd-mobile';
import moment from 'moment';
import { createForm } from 'rc-form';
import { router, withRouter } from 'umi';

import { defaultFormatResult, useRequest } from '@/hooks';
import useDictionary from '@/hooks/useDictionary';
import CustomNavBar from '@/pages/EntryManage/mobile/components/CustomNavBar';
import EntryMetaTag from '@/pages/EntryManage/mobile/components/EntryMetaTag';
import { fetchEmployeeArchivesData, saveEmployeeBasicInfo } from '@/pages/EntryManage/services';
import { useFormChange } from '@/pages/RecruitEmail/hooks';
import { Button, EditListItem, ListItem, Picker as PickerSingle, Radio } from '@/pages/RecruitEmail/mobile/components';
import { useAreaData } from '@/pages/Recruitment/External/hooks';

import ListItemHead from './components/ListItemHead';
import styles from './index.less';
import { formatDate } from './utils';

const PhoneType = props => (
    <div onClick={props.onClick} style={{ flex: 1, fontSize: 16, color: '#bcc1cd' }}>
        {props.extra} <Icon style={{ fontSize: 10 }} type="caret-down" />
    </div>
);

// 户籍类型选项
export const CENSUS_REGISTER_OPTIONS = [
    {
        value: 'HouseholdType1_local',
        label: '本地',
        children: [
            {
                value: 'HouseholdType2_town',
                label: '城镇'
            },
            {
                value: 'HouseholdType2_village',
                label: '农村'
            }
        ]
    },
    {
        value: 'HouseholdType1_outland',
        label: '外地',
        children: [
            {
                value: 'HouseholdType2_town_inner',
                label: '城镇（省内）'
            },
            {
                value: 'HouseholdType2_village_inner',
                label: '农村（省内）'
            },
            {
                value: 'HouseholdType2_town_outter',
                label: '城镇（省外）'
            },
            {
                value: 'HouseholdType2_village_outter',
                label: '农村（省外）'
            }
        ]
    }
];

/**
 * 入职员工基础信息
 */
const EntryEmployeeBasicMobile = ({ form, location }) => {
    const [pageError, setPageError] = useState();
    const { query } = location;
    const { entryPersonnelCode } = query;
    const { getFieldProps, getFieldValue, validateFields } = form;
    const { hasFormChange, initialForm } = useFormChange(form);

    const areaData = useAreaData();
    // 获取数据
    const {
        data: employeeArchivesData,
        loading: employeeArchivesLoading,
        error: fetchEmployeeArchivesInfoError
    } = useRequest(() => fetchEmployeeArchivesData(entryPersonnelCode), {
        refreshDeps: [entryPersonnelCode],
        ready: !!entryPersonnelCode,
        ...defaultFormatResult,
        onSuccess: () => {
            initialForm();
        }
    });
    // 提交
    const { run: submitRun, loading: submitLoading } = useRequest(submitData => saveEmployeeBasicInfo(submitData), {
        manual: true
    });
    const [sexTypeList] = useDictionary('sexType', { textKey: 'label' });
    // 是否显示户籍类型, 只用国籍是中国的才显示
    const [showHousehold, setShowHousehold] = useState(false);
    // 户籍类型
    // 国籍/户籍预处理
    const restoreArrayLinkString = data => (!data ? [] : data.split(','));
    const [firstHouseholdType, setFirstHouseholdType] = useState(undefined);
    const [secondHouseholdType, setSecondHouseholdType] = useState(undefined);
    const handleOnHouseHoldChange = record => {
        setShowHousehold(record?.[0] === '中国');
    };

    // mounted
    useEffect(() => {
        if (employeeArchivesData) {
            // 判断是否显示户籍类型
            handleOnHouseHoldChange(restoreArrayLinkString(employeeArchivesData?.nationalArea));
            setFirstHouseholdType(employeeArchivesData?.firstHouseholdType);
            setSecondHouseholdType(employeeArchivesData?.secondHouseholdType);
        }
    }, [employeeArchivesData]);

    // 提交
    const handleSubmit = () => {
        validateFields((err, values) => {
            if (!err) {
                const submitData = {
                    entryPersonnelCode,
                    // idPhoto: values?.idPhoto?.uploadResourceFile ? [values?.idPhoto?.uploadResourceFile] : [],
                    detailAddress: values.detailAddress,
                    birthday: moment(values?.birthday).format('YYYY-MM-DD'),
                    employeeName: values.employeeName,
                    employeeEnglishName: values.employeeEnglishName,
                    highestDegree: values.highestDegree,
                    idCard: values.idCard,
                    address: values.address?.join(','),
                    nationalArea: values.nationalArea?.join(','),
                    sex: values.sex,
                    email: values.email,
                    joinWorkTime: moment(values.joinWorkTime).format('YYYY-MM'),
                    areaCode: values.areaCode?.length && values.areaCode[0],
                    mobile: values.mobile
                };
                // 表单值预处理
                if (values?.firstHouseholdType) {
                    submitData.firstHouseholdType = values?.firstHouseholdType[0];
                    submitData.secondHouseholdType = values?.firstHouseholdType[1];
                }
                // 提交
                submitRun(submitData).then(res => {
                    if (res.code === 10000) {
                        Toast.info('保存成功', 3, null, false);
                        history.goBack();
                    } else {
                        Toast.info(res.msg);
                    }
                });
            } else {
                const errorList = Object.values(err);
                if (errorList && errorList.length > 0) {
                    const { errors } = errorList[0];
                    Toast.info(errors[0]?.message, 3, null, false);
                }
            }
        });
    };

    useLayoutEffect(() => {
        // 参数校验
        if (!entryPersonnelCode) {
            setPageError('参数无效');
        }
    }, [entryPersonnelCode]);

    const handleLeftClick = () => {
        if (hasFormChange()) {
            Modal.alert('存在未保存的内容，确定退出吗？', '', [
                { text: '取消' },
                {
                    text: '确定',
                    onPress: () => {
                        history.goBack();
                    }
                }
            ]);
        } else {
            history.goBack();
        }
    };

    if (pageError || fetchEmployeeArchivesInfoError) {
        return (
            <div className={styles.pageError}>
                {pageError?.msg || fetchEmployeeArchivesInfoError?.msg || '加载错误'}
            </div>
        );
    }

    return (
        <>
            {(employeeArchivesLoading || submitLoading) && <ActivityIndicator toast text="正在加载" />}
            {employeeArchivesData ? (
                <div className={styles.entryMobileContainer}>
                    <EntryMetaTag />
                    <CustomNavBar onLeftClick={handleLeftClick}>个人信息</CustomNavBar>
                    <div className="formContainer formContainerFixed">
                        {/* <ListItem
                            showArrow={false}
                            title={
                                <ListItemHead
                                    title="头像"
                                    content={
                                        <div className="upload">
                                            <AvatarUpload
                                                {...getFieldProps('idPhoto', {
                                                    initialValue: transformFileList(
                                                        [...(employeeArchivesData?.idPhoto?.[0]?.urlList || [])].splice(
                                                            -1,
                                                            1
                                                        )
                                                    )
                                                })}
                                                accept="image/*"
                                                businessCode="SysAvatar"
                                                categoryCode="idPhoto"
                                            />
                                        </div>
                                    }
                                />
                            }
                        /> */}
                        <EditListItem title="中文名" showArrow={false}>
                            <InputItem
                                {...getFieldProps('employeeName', {
                                    initialValue: employeeArchivesData?.employeeName || '',
                                    rules: [
                                        { required: true, message: '请输入中文名' },
                                        {
                                            validator(rule, value, callback) {
                                                // const employeeName = getFieldValue('employeeName');
                                                // const employeeEnglishName = getFieldValue('employeeEnglishName');
                                                // if (!employeeName && !employeeEnglishName) {
                                                //     callback('中文姓名和英文姓名不能同时为空!');
                                                // } else
                                                if (
                                                    /[`~!#$%^&*()+=<>?:"{}|~！#￥%……&*（）={}|《》？：“”【】、；‘’，。、]/g.test(
                                                        value
                                                    )
                                                ) {
                                                    callback('不允许输入特殊字符');
                                                } else {
                                                    callback();
                                                }
                                            }
                                        },
                                        {
                                            min: 2,
                                            max: 50,
                                            message: '中文姓名字数范围:2到50个字符'
                                        }
                                    ]
                                })}
                                clear
                                placeholder="请输入中文名"
                                // onBlur={() => validateFields(['employeeEnglishName'])}
                            />
                        </EditListItem>
                        <EditListItem title="英文名" showArrow={false}>
                            <InputItem
                                {...getFieldProps('employeeEnglishName', {
                                    initialValue: employeeArchivesData?.employeeEnglishName || '',
                                    rules: [
                                        {
                                            validator(rule, value, callback) {
                                                // const employeeName = getFieldValue('employeeName');
                                                // const employeeEnglishName = getFieldValue('employeeEnglishName');
                                                // if (!employeeName && !employeeEnglishName) {
                                                //     callback('中文姓名和英文姓名不能同时为空!');
                                                // } else
                                                if (
                                                    /[`~!#$%^&*()+=<>?:"{}|~！#￥%……&*（）={}|《》？：“”【】、；‘’，。、]/g.test(
                                                        value
                                                    )
                                                ) {
                                                    callback('不允许输入特殊字符');
                                                } else {
                                                    callback();
                                                }
                                            }
                                        },
                                        {
                                            min: 2,
                                            max: 50,
                                            message: '英文名字数范围:2到50个字符'
                                        }
                                    ]
                                })}
                                clear
                                placeholder="请输入英文名"
                                // onBlur={() => validateFields(['employeeName'])}
                            />
                        </EditListItem>
                        <ListItem
                            showArrow={false}
                            title={
                                <ListItemHead
                                    title="性别"
                                    content={
                                        <Radio
                                            dataSource={sexTypeList}
                                            {...getFieldProps('sex', {
                                                initialValue: employeeArchivesData?.sex,
                                                rules: [{ required: true, message: '请选择性别' }]
                                            })}
                                        />
                                    }
                                />
                            }
                        />
                        <EditListItem title="手机号" showArrow={false}>
                            <div style={{ display: 'flex', alignItems: 'center' }}>
                                <PickerSingle
                                    title="选择国际电话区号"
                                    className={styles.customPicker}
                                    data={[
                                        { label: '+86', value: '86' },
                                        { label: '+65', value: '65' }
                                    ]}
                                    cols={1}
                                    {...getFieldProps('areaCode', {
                                        initialValue: [employeeArchivesData?.areaCode || '86']
                                    })}
                                >
                                    <PhoneType />
                                </PickerSingle>
                                <div className={styles.mobileAddStyle}>
                                    <InputItem
                                        {...getFieldProps('mobile', {
                                            initialValue: employeeArchivesData?.mobile || '',
                                            rules: [
                                                {
                                                    required: true,
                                                    validator(rule, value, callback) {
                                                        const regex = /^\d{7,11}$/;
                                                        if (!value) {
                                                            callback('手机号不能为空');
                                                        } else if (!regex.test(value)) {
                                                            callback('手机号只能输入7-11位数字');
                                                        }
                                                        callback();
                                                    }
                                                }
                                            ]
                                        })}
                                        clear
                                        placeholder="请输入手机号"
                                    />
                                </div>
                            </div>
                        </EditListItem>
                        <EditListItem title="个人邮箱" showArrow={false}>
                            <InputItem
                                {...getFieldProps('email', {
                                    initialValue: employeeArchivesData?.email || '',
                                    rules: [
                                        { required: true, message: '请输入个人邮箱' },
                                        {
                                            pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
                                            message: '请输入正确的个人邮箱'
                                        },
                                        { max: 100, message: '邮箱字数不能超过100个字符' }
                                    ]
                                })}
                                clear
                                placeholder="请输入个人邮箱"
                            />
                        </EditListItem>
                        <EditListItem title="证件号码" showArrow={false}>
                            <InputItem
                                {...getFieldProps('idCard', {
                                    initialValue: employeeArchivesData?.idCard || '',
                                    rules: [
                                        {
                                            validator(rule, value, callback) {
                                                const regex = /(^\d{8}(0\d|10|11|12)([0-2]\d|30|31)\d{3}$)|(^\d{6}(18|19|20)\d{2}(0[1-9]|10|11|12)([0-2]\d|30|31)\d{3}(\d|X|x)$)/;
                                                if (!regex.test(value)) {
                                                    callback('请输入有效的证件号码（15位或18位数字或字母）');
                                                }
                                                callback();
                                            }
                                        }
                                    ]
                                })}
                                clear
                                placeholder="请输入证件号码"
                            />
                        </EditListItem>
                        <DatePicker
                            className={styles.customPicker}
                            mode="month"
                            title="出生年月"
                            extra="请选择"
                            format={formatDate}
                            minDate={new Date(0, 0, 0)}
                            maxDate={new Date()}
                            locale={{ okText: '确定', dismissText: '取消' }}
                            {...getFieldProps('birthday', {
                                initialValue:
                                    (employeeArchivesData?.birthday &&
                                        moment(employeeArchivesData?.birthday).toDate()) ||
                                    null,
                                rules: [{ required: true, message: '出生日期不能为空' }]
                            })}
                        >
                            <EditListItem title="出生年月">请选择</EditListItem>
                        </DatePicker>
                        <Picker
                            title="国籍/户籍"
                            className={styles.nationalAreaPicker}
                            data={areaData}
                            cols={4}
                            onVisibleChange={() => handleOnHouseHoldChange(getFieldValue('nationalArea'))}
                            format={labels => labels.join('/')}
                            {...getFieldProps('nationalArea', {
                                initialValue: employeeArchivesData?.nationalArea
                                    ? employeeArchivesData?.nationalArea.split(',')
                                    : undefined,
                                rules: [{ required: true, message: '请选择国籍/户籍' }]
                            })}
                        >
                            <EditListItem title="国籍/户籍">请选择</EditListItem>
                        </Picker>
                        {/* 户籍类型 */}
                        {showHousehold && (
                            <Picker
                                title="户籍类型"
                                className={styles.customPicker}
                                data={CENSUS_REGISTER_OPTIONS}
                                cols={2}
                                format={labels => labels.join('/')}
                                {...getFieldProps('firstHouseholdType', {
                                    initialValue:
                                        firstHouseholdType !== '' && secondHouseholdType !== ''
                                            ? [firstHouseholdType, secondHouseholdType]
                                            : undefined,
                                    rules: [{ required: true, message: '请选择户籍类型' }]
                                })}
                            >
                                <EditListItem title="户籍类型">请选择</EditListItem>
                            </Picker>
                        )}
                        <Picker
                            title="现居地"
                            className={styles.nationalAreaPicker}
                            data={areaData}
                            cols={4}
                            format={labels => labels.join('/')}
                            {...getFieldProps('address', {
                                initialValue: employeeArchivesData?.address
                                    ? employeeArchivesData?.address.split(',')
                                    : undefined
                            })}
                        >
                            <EditListItem title="现居地(选填)">请选择</EditListItem>
                        </Picker>
                        <EditListItem title="详细地址(选填)" showArrow={false}>
                            <TextareaItem
                                className="customTextarea"
                                autoHeight
                                rows={2}
                                count={200}
                                {...getFieldProps('detailAddress', {
                                    initialValue: employeeArchivesData?.detailAddress || '',
                                    rules: [
                                        {
                                            max: 200,
                                            message: '详细地址字数不能超过200个字符'
                                        }
                                    ]
                                })}
                                clear
                                placeholder="请输入"
                            />
                        </EditListItem>
                        <DatePicker
                            className={styles.customPicker}
                            mode="month"
                            format={formatDate}
                            minDate={new Date(0, 0, 0)}
                            maxDate={new Date()}
                            title="参加工作时间"
                            extra="请选择"
                            locale={{ okText: '确定', dismissText: '取消' }}
                            {...getFieldProps('joinWorkTime', {
                                initialValue:
                                    (employeeArchivesData?.joinWorkTime &&
                                        moment(employeeArchivesData?.joinWorkTime).toDate()) ||
                                    null,
                                rules: [{ required: true, message: '请选择参加工作时间' }]
                            })}
                        >
                            <EditListItem title="参加工作时间">请选择</EditListItem>
                        </DatePicker>
                    </div>
                    <div className="formControls">
                        <Button type="primary" onClick={handleSubmit}>
                            保存
                        </Button>
                    </div>
                </div>
            ) : null}
        </>
    );
};

export default withRouter(createForm()(EntryEmployeeBasicMobile));
